<?php

namespace app\admin\controller\order;

use app\api\service\OrderService;
use app\common\controller\Backend;
use think\Db;
use app\common\model\OrderProof;
use app\common\model\OrderLog;
use app\common\model\OrderAftersale;
use app\common\model\IncompleteBill;
use app\admin\model\Play;
use app\common\model\User;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\Reader\Csv;
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\MemoryDrawing;
use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * 订单管理
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{

    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\common\model\Order;
        $statusList = $this->model->getOrderStatusList();
        // unset($statusList[1]);
        $this->view->assign("statusList", $statusList);
        $this->db2 = Db::connect(config('database.db2'));
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        // 权限
        $auth_group_access = Db::name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
        $explode = explode(',', $auth_group_access);
        if ($this->request->isAjax()) {
            // 渠道分组
            $auth_group = $this->db2->name('auth_group')->where('pid',15)->select();
            $channel_group = [];
            foreach ($auth_group as $ag) {
                $channel_group[$ag['name']] = $ag['id'];
            }
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $ShopModel = new \app\admin\model\Shop();
            $PlayModel = new \app\admin\model\Play();
            $OrderProof = new OrderProof();
            $filter = input('filter','');
            $decode = json_decode($filter,1);
            $where2 = '1=1';
            if (isset($decode['play_order_no']) && $decode['play_order_no']) {
                if (intval($decode['play_order_no'])==0) {
                    $where2 .= ' and order.yunzhan_order_no = "'.$decode['play_order_no'].'"';
                } else {
                    $where2 .= ' and order.play_order_no = "'.$decode['play_order_no'].'"';
                }
            }
            if (isset($decode['service_admin_by']) && $decode['service_admin_by']) {
                $where2 .= ' and order.service_admin_by = "'.$decode['service_admin_by'].'"';
            }
            if (isset($decode['platform']) && $decode['platform']) {
                if ($decode['platform']=='美团') {
                    $where2 .= ' and order.platform_no = 1';
                } elseif ($decode['platform']=='饿了么') {
                    $where2 .= ' and order.platform_no = 2';
                } elseif ($decode['platform']=='京东') {
                    $where2 .= ' and order.platform_no = 3';
                }
            }
            if (isset($decode['shop_no']) && $decode['shop_no']) {
                $shop_no = $this->db2->name('shop')->where('id',$decode['shop_no'])->value('shop_no');
                if ($shop_no) {
                    $where2 .= ' and order.shop_no = "'.$shop_no.'"';
                }
            }
            if (isset($decode['is_yunzhan']) && $decode['is_yunzhan']) {
                if ($decode['is_yunzhan']>10) {
                    $decode['is_yunzhan'] = $decode['is_yunzhan']-10;
                    $where2 .= ' and order.is_yunzhan = '.$decode['is_yunzhan'].' and create_by="api"';
                } else {
                    $where2 .= ' and order.is_yunzhan = '.$decode['is_yunzhan'].' and create_by!="api"';
                }
            }
            if (isset($decode['shop_name']) && $decode['shop_name']) {
                $shop_no = $this->db2->name('shop')->where('shop_name like "%'.$decode['shop_name'].'%"')->value('group_concat(shop_no)');
                if ($shop_no) {
                    $where2 .= ' and order.shop_no in ('.$shop_no.')';
                } else {
                    $where2 .= ' and 1=2';
                }
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            if (in_array(5,$explode) && !in_array(1,$explode)) {
                $member = Db::name('admin')->where('leader',$this->auth->id)->value('group_concat(id)');
                $access_user = explode(',', $member);
                $access_user[] = $this->auth->id;
                $implode = implode(',', $access_user);
                $where2 .= ' and order.service_admin_id in ('.$implode.')';
            } elseif (in_array(3,$explode) && !in_array(1,$explode)) {// 业务员
                $where2 .= ' and order.service_admin_id='.$this->auth->id;
            }
            if (isset($decode['lat']) && $decode['lat']) {
                // 业务员
                $admin = $this->db2->name('admin')->where('id',$decode['lat'])->field('leader2')->find();
                $leader2 = explode(',', trim($admin['leader2'],','));
                $service_admin_ids = Db::name('admin')->where(['leader'=>['in',$leader2]])->value('group_concat(id)');
                $where2 .= ' and order.service_admin_id in ('.$service_admin_ids.')';
                // 渠道
                $ag = $this->db2->name('auth_group_access')->alias('aga')->join('chbc_auth_group ag','aga.group_id=ag.id')->where('aga.uid',$decode['lat'])->field('ag.*')->find();
                $is_yunzhan = $this->db2->name('channel')->where('name',$ag['name'])->value('id');
                $where2 .= ' and order.is_yunzhan='.$is_yunzhan.' and create_by!="api"';
            }
            $list = $this->db2->name('play_order')
                ->alias('order')
                ->field('order.*')
                ->where($where)
                ->where($where2)
                ->order($sort, $order)
                ->paginate($limit);
            $list2 = $list->items();

            foreach ($list2 as &$row) {
                $proof = $this->db2->name('play_order_proof')->where('play_order_no',$row['play_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,machine_audit_desc,machine_audit_state,deduction_beans,financial_review,financial_review_num')->find();
                $row['scheme_no_text'] = '图文反馈';
                if (!$proof['three_image']) $row['scheme_no_text'] = '无需反馈';
                if ($proof) {
                    if ($row['is_yunzhan']==0) {
                        $proof['one_image_url'] = strpos($proof['one_image'],'://')===false?config('chbc_upload_domain').$proof['one_image']:$proof['one_image'];
                        $proof['two_image_url'] = strpos($proof['two_image'],'://')===false?config('chbc_upload_domain').$proof['two_image']:$proof['two_image'];
                        $proof['three_image_url'] = strpos($proof['three_image'],'://')===false?config('chbc_upload_domain').$proof['three_image']:$proof['three_image'];
                    } else {
                        $proof['one_image_url'] = strpos($proof['one_image'],'://')===false?config('domain').$proof['one_image']:$proof['one_image'];
                        $proof['two_image_url'] = strpos($proof['two_image'],'://')===false?config('domain').$proof['two_image']:$proof['two_image'];
                        $proof['three_image_url'] = strpos($proof['three_image'],'://')===false?config('domain').$proof['three_image']:$proof['three_image'];
                    }
                }
                $row['proof'] = $proof;
                $row['platform'] = config('platform')[$row['platform_no']];
                $row['is_yunzhan'] = $row['is_yunzhan']==0?'吃喝不愁':$this->db2->name('channel')->where('id',$row['is_yunzhan'])->value('name');
                if ($row['create_by']=='api') $row['is_yunzhan'] = 'API-'.$row['is_yunzhan'];
                $shop = $ShopModel->where('shop_no',$row['shop_no'])->field('id,shop_name,middleman_id')->find();
                $row['shop_no'] = $shop['id'];
                $row['shop_name'] = $shop['shop_name'];
                // 减少渠道结算金额
                // $aftersale = $this->db2->name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$row['play_order_no']])->select();
                // if ($aftersale) {
                //     $deduction_beans=0;
                //     $financial_review_num=0;
                //     foreach ($aftersale as $key => &$value) {
                //         if ($value['content']) {
                //             $value['content'] = json_decode($value['content'],1);
                //             if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                //                 $deduction_beans+=$value['content']['yh']['amount'];
                //                 $financial_review_num+=$value['content']['sj']['amount'];
                //             }
                //             if ($value['type']=='修改渠道结算金额') {
                //                 $deduction_beans=$value['content']['value'];
                //             }
                //             if ($value['type']=='修改商家结算金额') {
                //                 $financial_review_num=$value['content']['value'];
                //             }
                //         }
                //     }
                //     if ($deduction_beans>0) $row['proof']['deduction_beans'] = $deduction_beans;
                //     if ($financial_review_num>0) $row['proof']['financial_review_num'] = $financial_review_num;
                // }
                // 渠道结算金额
                if (in_array($row['order_status'],[-8,-9])) {
                    // // 商家应该支付的：商家需要付的减商家扣款的
                    // $yf = round($row['rebate_amt']-$row['proof']['financial_review_num'],2);
                    // // 渠道应该获得的
                    // $qd = round($row['rebate_amt']-$row['service_charge_amt'],2);
                    // // 渠道实际获得的
                    // $row['actual_rebate_amt'] = round($qd-$row['proof']['deduction_beans'],2);
                    // // 平台服务费
                    // $row['service_charge_amt'] = round($yf-$row['actual_rebate_amt'],2);
                    
                    // $row['rebate_amt'] = $yf;
                    $row['actual_rebate_amt'] = $row['actual_rebate_amt2'];
                    $row['proof']['deduction_beans'] = round($row['rebate_amt']-$row['service_charge_amt']-$row['actual_rebate_amt'],2);
                    $row['service_charge_amt'] = $row['service_charge_amt2'];
                    $row['rebate_amt'] = round($row['service_charge_amt']+$row['actual_rebate_amt'],2);
                } elseif ($row['order_status']==-4) {
                    $row['actual_rebate_amt'] = 0;
                    $row['rebate_amt'] = 0;
                    $row['service_charge_amt'] = 0;
                } else {
                    $row['rebate_amt'] = round($row['service_charge_amt']+$row['actual_rebate_amt'],2);
                }
                // 渠道业务员
                $row['lat'] = '无';
                if ($row['is_yunzhan']!='吃喝不愁' && $row['create_by']!='api') {
                    // 活动所属的业务经理,如果group_id为5说明自身是经理，否则找他的上级
                    $auth_group_access = $this->db2->name('auth_group_access')->where(['uid'=>$row['service_admin_id'],'group_id'=>5])->find();
                    if (!$auth_group_access) {
                        $leader = $this->db2->name('admin')->where('id',$row['service_admin_id'])->value('leader');
                    } else {
                        $leader = $row['service_admin_id'];
                    }
                
                    if ($leader && isset($channel_group[$row['is_yunzhan']]) && $channel_group[$row['is_yunzhan']]) {
                        $admin = $this->db2->name('admin')->alias('a')->join('chbc_auth_group_access aga','aga.uid=a.id and aga.group_id='.$channel_group[$row['is_yunzhan']])->where('a.leader2 like "%,'.$leader.',%"')->field('a.id,a.nickname')->find();
                        if ($admin) $row['lat'] = $admin['nickname'];
                    }
                }
                // 经纪人佣金
                $row['service_admin_id'] = 0;
                if ($shop['middleman_id']) {
                    $middleman = $this->db2->name('middleman')->where('id',$shop['middleman_id'])->value('rebate_amt');
                    $row['service_admin_id'] = floatval($middleman);
                }
            }

            $result = array("total" => $list->total(), "rows" => $list2);

            return json($result);
        }
        $service_admin_id = [];
        if (in_array(5,$explode) && !in_array(1,$explode)) {
            $salesmanList = [];
            $member = Db::name('admin')->where('leader',$this->auth->id)->field('nickname')->select();
            foreach ($member as $key => $value) {
                $salesmanList[$value['nickname']] = $value['nickname'];
            }
        }elseif (in_array(1,$explode)) {
            $salesmanList = [];
            $salesman = $this->salesmanList();
            foreach ($salesman as $key => $value) {
                $salesmanList[$value['nickname']] = $value['nickname'];
            }
        } elseif (in_array(3,$explode) && !in_array(1,$explode)) {// 业务员
            $salesmanList = [];
            $salesmanList[$this->auth->nickname] = $this->auth->nickname;
        }
        $this->assignconfig(['salesmanList' => $salesmanList]);
        // 渠道搜索选项
        $channelList = [];
        $channel = $this->db2->name('channel')->where(['status'=>1])->select();
        foreach ($channel as $key => $value) {
            if ($value['id']==3) {
                $channelList[0] = $value['name'];
            } else {
                $channelList[$value['id']] = $value['name'];
                if ($value['clientId']) $channelList[$value['id']+10] = 'API-'.$value['name'];// API渠道
            }
        }
        $this->assignconfig(['channelList' => $channelList]);
        // 渠道业务员
        $qdywy = [];
        if (count($explode)==1 && in_array(3,$explode)) {
        } else {
            $quywy_group = Db::name('auth_group')->where('pid',15)->value('group_concat(id)');
            $quywy_user = Db::name('auth_group_access')->where('group_id in ('.$quywy_group.')')->value('group_concat(uid)');
            $admin = Db::name('admin')->where('id in ('.$quywy_user.')')->field('id,nickname')->select();
            foreach ($admin as $key => $value) {
                $qdywy[$value['id']] = $value['nickname'];
            }
        }
        $this->assignconfig(['qdywy' => $qdywy]);
        return $this->view->fetch();
    }

    /**
     * 编辑
     * 不满意反馈不在商家端显示
     */
    public function edit($ids = null)
    {
        if ($this->request->isPost()) {
            $row = $this->model->get($ids);
            if (!$row) {
                $this->error(__('No Results were found'));
            }
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                if (!in_array($row[$this->dataLimitField], $adminIds)) {
                    $this->error(__('You have no permission'));
                }
            }
            $params = $this->request->post("row/a");
            if (!isset($params['type']) || !$params['type']) {
                $this->success();
            }
            $play = Play::where('play_no',$row['play_no'])->find();
            $result = false;
            Db::startTrans();
            try {
                $User = new \app\common\model\User();
                $play_order_no = $row['play_order_no'];
                // 审核通过和驳回都是对于客户而言的
                switch ($params['type']) {
                    case '提交商家复审':
                        if ($row['order_status']!=2) {
                            $this->error('订单状态有误');
                        }
                        $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>0,'machine_audit_state'=>-1])->order('id DESC')->find();
                        if (!$orderProof) {
                            $this->error('提交有误');
                        }
                        // if ($orderProof['actual_pay']==0 && !$params['actual_pay']) {
                        //     $this->error('请填写用户实付金额');
                        // }
                        // $orderProof->actual_pay = $params['actual_pay'];
                        if (!isset($params['remark']) || !$params['remark']) {
                            $params['remark'] = '';
                        }
                        $params['remark'] = str_replace('（', '(', $params['remark']);
                        $params['remark'] = str_replace('）', ')', $params['remark']);
                        $remark = $params['remark'];
                        $orderProof->handle_admin_id = $this->auth->id;
                        $orderProof->handle_admin_desc = $this->auth->nickname.'（'.$remark.'）确认通过审核';
                        $orderProof->handle_status = 1;
                        $orderProof->handle_time = time();
                        $orderProof->save();
                        $this->orderLog($row->id,$play_order_no,'客服审核通过，待商家复审',$this->auth->nickname,$this->auth->id);
                        // 如果是扣吃豆通过
                        $beans = $row['actual_rebate_amt'];
                        if (isset($params['amount']) && $params['amount']) {
                            $beans = $row['actual_rebate_amt']-$params['amount'];
                            if ($row['is_yunzhan']==0) {
                                // 活动里的实际支付总额
                                $play->acture_total_money = $play->acture_total_money==0?$beans:$play->acture_total_money-$params['amount'];
                                $play->save();
                            }
                            $orderProof->deduction_beans = $params['amount'];
                            $orderProof->financial_review_num = $params['amount'];
                        }
                        $row->is_fushen = 1;
                        // 实际返豆
                        $row->actual_rebate_amt = $beans;
                        // 订单状态
                        $row->order_status = 6;
                        $row->update_by = $this->auth->id;
                        $row->save();
                        break;
                    case '审核通过':
                        if (!in_array($row['order_status'],[2,-7])) {
                            $this->error('订单状态有误');
                        }
                        if ($row['order_status']==2) {
                            $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>0,'machine_audit_state'=>-1])->order('id DESC')->find();
                            if (!$orderProof) {
                                $this->error('提交有误');
                            }
                            // if ($orderProof['actual_pay']==0 && !$params['actual_pay']) {
                            //     $this->error('请填写用户实付金额');
                            // }
                            // $orderProof->actual_pay = $params['actual_pay'];
                            if (!isset($params['remark']) || !$params['remark']) {
                                $params['remark'] = '';
                            }
                            $params['remark'] = str_replace('（', '(', $params['remark']);
                            $params['remark'] = str_replace('）', ')', $params['remark']);
                            $remark = $params['remark'];
                            $orderProof->handle_admin_id = $this->auth->id;
                            $orderProof->handle_admin_desc = $this->auth->nickname.'（'.$remark.'）确认通过审核';
                            // 用户吃豆增加
                            $beans = $row['actual_rebate_amt'];
                            // 如果是扣吃豆通过
                            if (isset($params['amount']) && $params['amount']) {
                                $beans = $row['actual_rebate_amt']-$params['amount'];
                                $orderProof->deduction_beans = $params['amount'];
                                $orderProof->financial_review_num = $params['amount'];
                                // 售后事件
                                $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname, $this->auth->id, '完成前扣款', $orderProof['play_order_no'], $row['play_no'],json_encode($params,JSON_UNESCAPED_UNICODE));
                            }
                            // 实际返豆
                            $row->actual_rebate_amt = $beans;
                            // 订单状态
                            $row->order_status = 3;
                            $row->update_by = $this->auth->id;
                            $row->save();
                        }
                        // 这里表示通过用户的凭证，驳回商家的异常提交
                        if ($row['order_status']==-7) { // 商家提交异常审核
                            // 商家部分的数据
                            $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>0])->order('id DESC')->find();
                            if (!$orderProof || !$orderProof['order_aftersale_id']) {
                                $this->error('提交有误');
                            }
                            // if (!$params['sj']['desc'] || $params['sj']['desc']!=3) {
                            //     $this->error('受理意见选择有误');
                            // }
                            if (!$params['yh']['file']) {
                                $this->error('请上传用户凭证');
                            }
                            if ($params['sj']['desc']!=3) {
                                $this->error('请选择提交财务');
                            }
                            $params['sj']['amount'] = floatval($params['sj']['amount']);
                            $params['yh']['amount'] = floatval($params['yh']['amount']);
                            // 用户吃豆增加
                            $beans = $row['actual_rebate_amt'];
                            // 售后事件
                            $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname, $this->auth->id, '确认通过审核', $orderProof['play_order_no'], $row['play_no'],json_encode($params,JSON_UNESCAPED_UNICODE));
                            $orderProof->order_aftersale_id = $OrderAftersaleId;
                            $orderProof->yh_remark = $params['yh']['remark'];
                            $orderProof->sj_remark = $params['sj']['remark'];
                            $orderProof->financial_review = $params['sj']['desc'];
                            $orderProof->financial_review_num = $orderProof->financial_review_num+$params['sj']['amount'];
                            $orderProof->aftersale_evidence = $params['yh']['file'];
                            $orderProof->deduction_beans = $orderProof->deduction_beans+$params['yh']['amount'];
                            // 订单状态
                            $row->order_status = -9;
                            $row->update_by = $this->auth->id;
                            // 减少渠道结算金额
                            $aftersale = Db::name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$row['play_order_no']])->select();
                            $deduction_beans=0;
                            $financial_review_num=0;
                            if ($aftersale) {
                                foreach ($aftersale as $key => &$value) {
                                    if ($value['content']) {
                                        $value['content'] = json_decode($value['content'],1);
                                        if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                                            $deduction_beans+=$value['content']['yh']['amount'];
                                            $financial_review_num+=$value['content']['sj']['amount'];
                                        }
                                        if ($value['type']=='修改渠道结算金额') {
                                            $deduction_beans=$value['content']['value'];
                                            $this->error('填写过“修改渠道结算金额”，不能再提交异常');
                                        }
                                        if ($value['type']=='修改商家结算金额') {
                                            $financial_review_num=$value['content']['value'];
                                            $this->error('填写过“修改商家结算金额”，不能再提交异常');
                                        }
                                    }
                                }
                            }
                            if ($deduction_beans==0) $deduction_beans += $params['yh']['amount'];
                            if ($financial_review_num==0) $financial_review_num += $params['sj']['amount'];
                            // 渠道结算金额
                            // 商家应该支付的：商家需要付的减商家扣款的
                            $yf = round($row['rebate_amt']-$financial_review_num,2);
                            // 渠道应该获得的
                            $qd = round($row['rebate_amt']-$row['service_charge_amt'],2);
                            // 渠道实际获得的
                            $row->actual_rebate_amt2 = round($qd-$deduction_beans,2);
                            // 重新计算后的平台服务费
                            $row->service_charge_amt2 = round($yf-$row->actual_rebate_amt2,2);
                            $row->save();
                        }
                        //
                        $orderProof->handle_status = 1;
                        $orderProof->handle_time = time();
                        $orderProof->save();
                        $this->orderLog($row->id,$play_order_no,'客服审核通过',$this->auth->nickname,$this->auth->id);
                        break;
                    case '驳回审核': // 第一次驳回后用户还有一次提交机会
                        if (!in_array($row['order_status'],[2,-7,-5])) {
                            $this->error('订单状态有误2');
                        }
                        if ($row['order_status']==2 || $row['order_status']==-5) {
                            $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>0,'machine_audit_state'=>-1])->order('id DESC')->find();
                            if (!$orderProof) {
                                $this->error('提交有误');
                            }
                            if (!isset($params['remark']) || !$params['remark']) {
                                $params['remark'] = '';
                            }
                            $params['remark'] = str_replace('（', '(', $params['remark']);
                            $params['remark'] = str_replace('）', ')', $params['remark']);
                            $remark = $params['remark'];
                            $orderProof->handle_admin_id = $this->auth->id;
                            $orderProof->handle_admin_desc = $this->auth->nickname.'（'.$remark.'）驳回用户订单申请';
                        }
                        $orderProof->handle_status = -1;
                        $orderProof->handle_time = time();
                        $orderProof->save();
                        // 订单状态
                        $row->order_status = -3;
                        $row->update_by = $this->auth->id;
                        $row->save();
                        $this->orderLog($row->id,$play_order_no,'客服审核不通过',$this->auth->nickname,$this->auth->id);
                        // 产生售后事件
                        $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'驳回订单',$orderProof['play_order_no'],$row['play_no'],json_encode(['remark'=>$params['remark']],JSON_UNESCAPED_UNICODE));
                        break;
                    case '提交异常':
                        if ($row['order_status']!=3 && $row['order_status']!=-9 && $row['order_status']!=-6 && $row['order_status']!=6) {
                            $this->error('订单状态有误3');
                        }
                        if (!isset($params['img']) || !$params['img']) {
                            $this->error('请提交异常凭证');
                        }
                        if (!isset($params['desc']) || !$params['desc']) {
                            $this->error('请提交异常反馈');
                        }
                        if (!isset($params['remark']) || !$params['remark']) {
                            $params['remark']='';
                        }
                        $params['remark'] = str_replace(' ', '', $params['remark']);
                        // 备注不是必填
                        $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>1])->order('id DESC')->find();
                        if (!$orderProof) {
                            $this->error('提交有误');
                        }
                        // 产生售后事件
                        $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'业务员提交异常',$orderProof['play_order_no'],$row['play_no'],json_encode(['desc'=>$params['desc'],'img'=>$params['img'],'remark'=>$params['remark']],JSON_UNESCAPED_UNICODE));

                        $orderProof->handle_status = 0;
                        $orderProof->yc_remark = $params['remark'];
                        $orderProof->order_aftersale_id = $OrderAftersaleId;
                        $orderProof->handle_merchant_id = $this->auth->id;
                        $orderProof->handle_merchant_desc = json_encode(['desc'=>$params['desc'],'img'=>$params['img'],'remark'=>$params['remark']],JSON_UNESCAPED_UNICODE);
                        $orderProof->save();
                        // 订单状态
                        $row->order_status = -7;
                        $row->update_by = $this->auth->id;
                        $row->save();
                        $this->orderLog($row->id,$play_order_no,'业务员帮商家提交异常',$this->auth->nickname,$this->auth->id);
                        if ($row['is_yunzhan']==0) {
                            \fast\Http::get(config('chbc_domain').'/index/yunzhan/notify?order_sn='.$play_order_no.'&state=-7&source=2&origin=bdb&img='.config('upload_domain').$params['img'].'&desc='.$params['desc'].'&remark='.$params['remark']);
                        }
                        break;
                    case '提交财务':  // 售后客服处理商家提交异常或扣吃豆通过后提交财务
                        if (!in_array($row['order_status'],[2,-7])) {
                            $this->error('订单状态有误4');
                        }
                        // if ($row['order_status']==2) { // 扣吃豆通过
                        //     if (!$params['reason'] || !$params['amount']) {
                        //         $this->error('请填写扣款原因，扣款金额');
                        //     }
                        //     $orderProof = orderProof::where(['play_order_no'=>$row['play_order_no'],'handle_status'=>0,'machine_audit_state'=>-1])->find();
                        //     if (!$orderProof) {
                        //         $this->error('提交有误');
                        //     }
                        //     $orderProof->handle_admin_id = $this->auth->id;
                        //     $orderProof->handle_admin_desc = $this->auth->nickname.'拟扣吃豆通过：'.$params['reason'];
                        
                        //     $this->orderLog($row->id,$row->play_order_no,'客服审核拟取消或扣吃豆通过，数量:'.$params['amount'] ,$this->auth->nickname,$this->auth->id);
                        // }
                        if ($row['order_status']==-7) { // 商家提交异常审核，客服提交给财务
                            $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>0])->order('id DESC')->find();
                            if (!$orderProof || !$orderProof['order_aftersale_id']) {
                                $this->error('提交有误');
                            }
                            if (!$params['sj']['desc']) {
                                $this->error('请选择受理意见');
                            }
                            if (!isset($params['sj']['amount'])) {
                                $this->error('请填写退款金额');
                            }
                            if (!$params['yh']['file']) {
                                $params['yh']['file']='';
                            }
                            // if (!$params['yh']['amount']) {
                            //     $this->error('请填写扣款金额');
                            // }
                            if ($params['sj']['desc']==3) {
                                $this->error('请选择审核通过');
                            }
                            $params['sj']['amount'] = floatval($params['sj']['amount']);
                            $params['yh']['amount'] = floatval($params['yh']['amount']);
                            // 售后事件
                            $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'客服审核拟取消或扣吃豆通过',$orderProof['play_order_no'],$row['play_no'],json_encode($params,JSON_UNESCAPED_UNICODE));
                            $orderProof->order_aftersale_id = $OrderAftersaleId;
                            $row->order_status = -8;
                            $row->update_by = $this->auth->id;
                            // 减少渠道结算金额
                            $aftersale = Db::name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$row['play_order_no']])->select();
                            $deduction_beans=0;
                            $financial_review_num=0;
                            if ($aftersale) {
                                foreach ($aftersale as $key => &$value) {
                                    if ($value['content']) {
                                        $value['content'] = json_decode($value['content'],1);
                                        if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                                            $deduction_beans+=$value['content']['yh']['amount'];
                                            $financial_review_num+=$value['content']['sj']['amount'];
                                        }
                                        if ($value['type']=='修改渠道结算金额') {
                                            $deduction_beans=$value['content']['value'];
                                            $this->error('填写过“修改渠道结算金额”，不能再提交异常');
                                        }
                                        if ($value['type']=='修改商家结算金额') {
                                            $financial_review_num=$value['content']['value'];
                                            $this->error('填写过“修改商家结算金额”，不能再提交异常');
                                        }
                                    }
                                }
                            }
                            if ($deduction_beans==0) $deduction_beans += $params['yh']['amount'];
                            if ($financial_review_num==0) $financial_review_num += $params['sj']['amount'];
                            // 渠道结算金额
                            // 商家应该支付的：商家需要付的减商家扣款的
                            $yf = round($row['rebate_amt']-$financial_review_num,2);
                            // 渠道应该获得的
                            $qd = round($row['rebate_amt']-$row['service_charge_amt'],2);
                            // 渠道实际获得的
                            $row->actual_rebate_amt2 = round($qd-$deduction_beans,2);
                            // 重新计算后的平台服务费
                            $row->service_charge_amt2 = round($yf-$row->actual_rebate_amt2,2);
                            $row->save();
                        
                            $this->orderLog($row->id,$play_order_no,'客服审核拟退还商家部分余额，数量:'.$params['sj']['amount'],$this->auth->nickname,$this->auth->id);
                            
                            $this->orderLog($row->id,$play_order_no,'客服审核拟扣除用户部分吃豆，数量:'.$params['yh']['amount'],$this->auth->nickname,$this->auth->id);

                            $orderProof->handle_admin_id = $this->auth->id;
                            if (isset($params['yh']['remark']) && $params['yh']['remark']) {
                                $params['yh']['remark'] = str_replace('（', '(', $params['yh']['remark']);
                                $params['yh']['remark'] = str_replace('）', ')', $params['yh']['remark']);
                            }
                            $orderProof->handle_admin_desc = $this->auth->nickname.'（'.$params['yh']['remark'].'）确认通过审核';
                            $orderProof->yh_remark = $params['yh']['remark'];
                            $orderProof->sj_remark = $params['sj']['remark'];
                            $orderProof->financial_review = $params['sj']['desc'];
                            $orderProof->financial_review_num = $params['sj']['amount'];
                            $orderProof->aftersale_evidence = $params['yh']['file'];
                            $orderProof->deduction_beans = $params['yh']['amount'];
                        }

                        // 
                        $orderProof->handle_status = 2;
                        $orderProof->save();
                        $params['yh']['file'] = config('upload_domain').$params['yh']['file'];
                        break;
                    case '财务已处理':// 售后客服处理商家提交异常或扣吃豆通过后财务处理
                        if (!in_array($row['order_status'],[2,-8])) {
                            $this->error('订单状态有误5');
                        }
                        // if (!$params['financial_review']) {
                        //     $this->error('请填写财务处理');
                        // }
                        // if ($params['financial_review']==2 && !$params['bill']) {
                        //     $this->error('请填写修改账单金额');
                        // }
                        // if ($row['order_status']==2) { // 扣吃豆通过
                        //     $orderProof = orderProof::where(['play_order_no'=>$row['play_order_no'],'handle_status'=>2,'machine_audit_state'=>-1])->find();
                        //     if (!$orderProof) {
                        //         $this->error('提交有误');
                        //     }
                        // }
                        // 商家提交异常审核，客服提交给财务
                        $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>2])->order('id DESC')->find();
                        if (!$orderProof || !$orderProof['order_aftersale_id']) {
                            $this->error('提交有误');
                        }
                        // 售后事件
                        $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'财务已处理',$orderProof['play_order_no'],$row['play_no'],'');
                        $orderProof->order_aftersale_id = $OrderAftersaleId;
                        // 
                        if ($orderProof['financial_review']==1) { // 取消
                            $beans = -1*$orderProof['deduction_beans'];

                            $orderProof->handle_status = 3;
                            $orderProof->handle_time = time();
                            $orderProof->save();
                            // 订单状态
                            $row->order_status = -4;
                            $row->update_by = $this->auth->id;
                            $row->actual_rebate_amt = $row->actual_rebate_amt-$orderProof['financial_review_num'];
                            $row->save();
                            $this->orderLog($row->id,$play_order_no,'异常已取消',$this->auth->nickname,$this->auth->id);

                            // 经纪人佣金退还
                            $middlemanyj = $this->db2->name('user_money_log')->where(['log_type'=>12,'tran_no'=>$orderProof['play_order_no']])->find();
                            if ($middlemanyj) {
                                $money = -1*$middlemanyj['money'];
                                $User->money($money, $middlemanyj['user_id'], '异常订单收回佣金', $middlemanyj['tran_no']);
                            }
                            // 更新商家账单
                            // if ($row['is_yunzhan']==0) {
                                $bill_list = $this->db2->name('bill_list')->order('id DESC')->find();
                                $where = 'create_dt="'.$bill_list['create_dt'].'" and shop_no='.$row['shop_no'];
                                $bill_list = $this->db2->name('bill_list')->where($where)->field('*')->find();
                                if ($bill_list) {
                                    $time = time();
                                    $update = [];
                                    $play_status = '正常';
                                    $last_pay_time = $time;// 到账时间
                                    $sum = $bill_list['total_money']-$orderProof['financial_review_num'];
                                    $update['last_pay_time'] = 0;
                                    $update['total_money'] = 0;
                                    $update['pay_status'] = '';
                                    $update['nopay_dt'] = '1970-01-01 00:00:00';
                                    if ($sum>0) {
                                        $update['pay_status'] = '待支付';
                                        $update['total_money'] = round($sum,2);
                                        $order = $this->db2->name('play_order')->field('create_dt')->where(['shop_no'=>$row['shop_no']])->where('is_pay=0 and order_status in (3,6,-9) and create_dt<"'.substr($bill_list['create_dt'], 0,10).'"')->order('create_dt asc')->find();
                                        if ($order) {
                                            $update['nopay_dt'] = $order['create_dt'];
                                        }
                                    } else {
                                        $update['pay_status'] = '已支付';
                                        $update['last_pay_time'] = $last_pay_time;
                                    }
                                    $update['play_status'] = $play_status;
                                    $update['update_dt'] = date('Y-m-d H:i:s',time());
                                    Db::name('bill_list')->where('id='.$bill_list['id'])->update($update);
                                }
                            // }
                        } else { // 修改金额
                            $rebate_amt = $row->rebate_amt;
                            $actual_rebate_amt = $row->actual_rebate_amt;

                            $orderProof->handle_status = 1;
                            $orderProof->handle_time = time();
                            $orderProof->save();
                            // 订单状态
                            $row->order_status = -9;
                            $row->update_by = $this->auth->id;
                            $row->actual_rebate_amt = $actual_rebate_amt-$orderProof['financial_review_num'];
                            $row->save();
                            
                            $this->orderLog($row->id,$play_order_no,'财务已处理',$this->auth->nickname,$this->auth->id);
                            $beans = -1*$orderProof['deduction_beans'];
                        }
                        if ($row['is_pay']==1) {
                            // 先计算之前总共扣了多少
                            $sum = (float)Db::name('user_money_log')->where(['tran_no'=>$orderProof['play_order_no'],'log_type'=>7])->value('sum(money)');
                            // 计算本次应该给商家退多少
                            $back = round($orderProof['financial_review_num']-$sum,2);
                            $shop = Db::name('shop')->where('shop_no',$row['shop_no'])->find();
                            if (!isset($shop['phone']) || !$shop['phone']) $this->error('相关店铺信息需要完善');
                            $merchant = Db::name('user')->where('mobile',$shop['phone'])->find();
                            // 如果有对应商家，则给商家加上余额，如果没有对应商家，插入一条手机号流水
                            if ($merchant) {
                                $res = $User->money($back, $merchant['id'], '财务修改账单金额', $orderProof['play_order_no']);
                            } else {
                                // 先查询这个手机号之前有没有流水
                                $before = (float)Db::name('user_money_log')->where(['phone'=>$shop['phone'],'log_status'=>0])->order('id desc')->value('after_money');
                                $money = $back;
                                $after = function_exists('bcadd') ? bcadd($before, $money, 2) : $before + $money;
                                //写入日志
                                \app\common\model\UserMoneyLog::create(['phone' => $shop['phone'], 'money' => $money, 'before_money' => $before, 'after_money' => $after, 'memo' => '财务修改账单金额','log_type'=>7,'log_status'=>0,'tran_no'=>$orderProof['play_order_no']]);
                            }
                        }
                        break;
                    case '不满意通过':
                        if (!in_array($row['order_status'],[-5,2])) {
                            $this->error('订单状态有误6');
                        }
                        $orderProof = orderProof::where(['play_order_no'=>$play_order_no,'handle_status'=>0,'machine_audit_state'=>-1])->order('id DESC')->find();
                        if (!$orderProof) {
                            $this->error('提交有误');
                        }
                        if (!isset($params['remark']) || !$params['remark']) {
                            $params['remark'] = '';
                        }
                        $params['remark'] = str_replace('（', '(', $params['remark']);
                        $params['remark'] = str_replace('）', ')', $params['remark']);
                        $remark = $params['remark'];
                        $orderProof->handle_admin_id = $this->auth->id;
                        $orderProof->handle_admin_desc = $this->auth->nickname.'（'.$remark.'）确认不满意通过';
                        // 用户吃豆增加
                        $beans = $row['actual_rebate_amt'];
                        // 如果是扣吃豆通过
                        if (isset($params['amount']) && $params['amount']) {
                            $beans = $row['actual_rebate_amt']-$params['amount'];
                            // 活动里的实际支付总额
                            if ($row['is_yunzhan']==0) {
                                $play->acture_total_money = $play->acture_total_money==0?$beans+$row['service_charge_amt']:$play->acture_total_money-$params['amount'];
                                $play->save();
                                // 如果商家冻结了余额
                                if (isset($play['is_pay']) && $play['is_pay']==1) {
                                    // 冻结金额减少
                                    $money = -1*$params['amount'];
                                    $User->money($money, $orderProof['merchant_id'], '冻结返还', $orderProof['play_order_no'], 1);
                                    // 余额增加
                                    if ($money<0) {
                                        $money = $params['amount'];
                                        $User->money($money, $orderProof['merchant_id'], '冻结返还', $orderProof['play_order_no']);
                                    }
                                }
                            }
                            $orderProof->deduction_beans = $params['amount'];
                            $orderProof->financial_review_num = $params['amount'];
                        }
                        //
                        $orderProof->handle_status = 1;
                        $orderProof->handle_time = time();
                        $orderProof->save();
                        // 订单状态
                        $row->order_status = -6;
                        $row->update_by = $this->auth->id;
                        $row->save();
                        $this->orderLog($row->id,$play_order_no,'客服不满意通过',$this->auth->nickname,$this->auth->id);
                        // 不满意通过名额加回去
                        // if ($row['is_yunzhan']==0) {
                        //     $play->stock = $play->stock+1;
                        //     $play->save();
                        // }
                        // 用户吃豆增加
                        // $beans = $row['actual_rebate_amt'];
                        $User->beans($beans,$row['user_id'],'下单返豆',$orderProof['play_order_no']);
                        // 前台发布活动，当前这一单冻结金额减少
                        if ($play['pay_status']==3 && $play['is_pay']==1) {
                            // 当前这一单冻结金额减少
                            $money = -1*($row['actual_rebate_amt']+$row['service_charge_amt']);
                            (new \app\common\model\User())->money($money, $play['user_id'], '商家结算', $orderProof['play_order_no'], 1);
                            $row->is_pay = 1;
                            $row->pay_time = time();
                            $row->save();
                        }
                        if ($row['order_status']==-6) {
                            $user = $User->get($row['user_id']);
                            // 发送微信消息
                            $qywx = $this->db2->name('qywx_receive')->where('user_id',$user['id'])->field('id,UserID,ExternalUserID')->find();
                            if ($qywx) {
                                $external_userid = $qywx['ExternalUserID'];
                                $sender = $qywx['UserID'];
                                $title = '您的活动订单审核成功';
                                $picurl = config('upload_domain').'/uploads/20230422/baca91c2f33a6d1270aae65ea4d3dc79.png';
                                $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                                $url = config('h5_domain').'/#/pages/index/order';
                                $lPublics = new \app\api\service\UserService();
                                $res = $lPublics->qywxPush($external_userid,$sender,$title,$picurl,$desc,$url,$user['id']);
                            }
                            // 发送app消息
                            // if (isset($user['birthday']) && $user['birthday']) {
                                $lPublics = new \app\api\service\UserService();
                                $title = '您的活动订单审核成功';
                                $desc = '恭喜完成订单，获得'.$beans.'吃豆';
                                $url = '/pages/index/order';
                                $res = $lPublics->pushChat($user['birthday'],$title,$desc,$url,$user['id'],$play_order_no);
                            // }
                        }
                        break;
                    case '取消订单':
                        if (!in_array($row['order_status'],[2,-3])) {
                            $this->error('订单状态有误');
                        }
                        $orderProof = orderProof::where(['play_order_no'=>$play_order_no])->order('id DESC')->find();
                        if (!$orderProof) {
                            $this->error('提交有误');
                        }
                        if (!isset($params['remark']) || !$params['remark']) {
                            $params['remark'] = '';
                        }
                        $params['remark'] = str_replace('（', '(', $params['remark']);
                        $params['remark'] = str_replace('）', ')', $params['remark']);
                        $remark = $params['remark'];
                        $orderProof->handle_admin_id = $this->auth->id;
                        $orderProof->handle_admin_desc = $this->auth->nickname.'（'.$remark.'）取消用户订单';
                        $orderProof->handle_time = time();
                        $orderProof->save();
                        // 订单状态
                        $row->order_status = -1;
                        $row->update_by = $this->auth->id;
                        $row->cancel_reason = 4;
                        $row->save();
                        $this->orderLog($row->id,$play_order_no,'后台取消订单',$this->auth->nickname,$this->auth->id);
                        // 名额
                        $play->stock = $play->stock+1;
                        $play->save();
                        // 产生售后事件
                        $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'审核取消订单',$orderProof['play_order_no'],$row['play_no'],json_encode(['remark'=>$params['remark']],JSON_UNESCAPED_UNICODE));
                        break;
                    case '商家复审合格':
                        if (!in_array($row['order_status'],[6])) {
                            $this->error('订单状态有误');
                        }
                        $orderProof = orderProof::where(['play_order_no'=>$play_order_no])->order('id DESC')->find();
                        if (!$orderProof) {
                            $this->error('提交有误');
                        }
                        $beans = $row->actual_rebate_amt;
                        $User->beans($beans,$row['user_id'],'下单返豆',$orderProof['play_order_no']);
                        // 实际返豆
                        $row->actual_rebate_amt = $beans;
                        // 订单状态
                        $row->order_status = 3;
                        $row->update_by = $this->auth->id;
                        $row->save();
                        $this->orderLog($row->id,$play_order_no,'客服审核通过',$this->auth->nickname,$this->auth->id);
                        break;
                    case '恢复订单':
                        if (!in_array($row['order_status'],[-1,-2])) {
                            $this->error('订单状态有误');
                        }
                        // 活动是否完成
                        if ($play['chbcconsume']==0) {
                            $this->error('当前活动无名额');
                        }
                        $time1 = strtotime($row['create_dt']);
                        $time2 = strtotime(date('Y-m-d'));
                        if ($time1-$time2>86400 || $time2-$time1>86400) {
                            $this->error('只能恢复近2天的订单');
                        }
                        $play_order_log = $this->db2->name('play_order_log')->field('info')->where('play_order_no',$row['play_order_no'])->select();
                        // 是否是已驳回的订单
                        $is_rejected = 0;
                        foreach ($play_order_log as $key => $value) {
                            if ($value['info']=='客服审核不通过') {
                                $is_rejected = 1;break;
                            }
                        }
                        if ($is_rejected==1) {
                            $row->order_status=-3;
                        } else {
                            $row->order_status=1;
                        }
                        $expire_time = intval(time()+7200);
                        $row->expire_time = $expire_time;
                        $row->save();
                        $row->expire_time = $expire_time;
                        $row->save();
                        if ($play) {
                            $play->stock = $play->stock-1;
                            $play->chbcconsume = $play->chbcconsume-1;
                            $play->save();
                            $Redis = new \think\cache\driver\Redis();
                            if ($Redis->has('bdbplay'.$play['id'])) {
                                $Redis->dec('bdbplay'.$play['id']);
                            }
                        }
                        $this->orderLog($row->id,$play_order_no,'客服恢复订单',$this->auth->nickname,$this->auth->id);
                        break;
                    
                }
                // $complete_order = $this->model->where(['play_no'=>$row['play_no'],'order_status'=>['in',[3,6,-9]]])->count();
                // 状态改为待支付
                // if (($complete_order==$play['chbcquota'] && $play['play_status']==2) || ($play['play_status']==4 && $complete_order==$play['chbcquota']-$play['chbcconsume'] && $play['chbcquota']-$play['chbcconsume']>0)) {
                //         $play->play_status = 3;
                //         $play->acture_total_money = (float)$this->model->where(['play_no'=>$row['play_no'],'order_status'=>['in',[3,6,-9]]])->value('sum(actual_rebate_amt+service_charge_amt)');
                //         $play->save();
                // }
                // 分销和抽奖机会和积分
                if ($row->order_status==3 || ($row->order_status==-9 && $row->is_fushen==1)) {
                    // 中间人佣金
                    if ($play['is_pay']==1) {
                        $shop = Db::name('shop')->where(['shop_no'=>$row['shop_no']])->field('middleman_id,shop_no')->find();
                        $middleman = Db::name('middleman')->where(['id'=>$shop['middleman_id']])->field('rebate_amt,user_id')->find();
                        if (isset($middleman['rebate_amt']) && $middleman['rebate_amt']) {
                            (new \app\common\model\User())->money($middleman['rebate_amt'], $middleman['user_id'], '经纪人收益', $play_order_no);
                        }
                    }
                    $this->orderLog($row->id,$play_order_no,'订单完成',$this->auth->nickname,$this->auth->id);
                }
                
                // 给渠道发通知
                if ($row['create_by']=='api') {
                    $OrderService = new \app\open\service\OrderService();
                    $debitAmount = 0;
                    $settlementAmount = round($row['actual_rebate_amt']+$row['service_charge_amt'],2);
                    if ($row->order_status==3) {
                        if (isset($OrderAftersaleId)) {
                            $OrderService->deduction($OrderAftersaleId,$orderProof['play_order_no'],$params['amount'],$remark,$row['is_yunzhan'],$row['order_status']);
                            $debitAmount = $params['amount'];
                        }
                        $OrderService->statusChange($orderProof['wm_order_sn'],$orderProof['play_order_no'],$row['order_status'],$debitAmount,$settlementAmount,$row['is_yunzhan']);
                    } elseif ($row->order_status==-9 || $row->order_status==-4) {
                        $debitAmount = $orderProof['deduction_beans'];
                        $handle_merchant_desc = json_decode($orderProof['handle_merchant_desc'],1);
                        $remark = '';
                        if (isset($handle_merchant_desc['desc'])) $remark = $handle_merchant_desc['desc'];
                        $OrderService->deduction($OrderAftersaleId,$orderProof['play_order_no'],$orderProof['deduction_beans'],$remark,$row['is_yunzhan'],3);
                        // $OrderService->statusChange($orderProof['wm_order_sn'],$orderProof['play_order_no'],$row['order_status'],$debitAmount,$settlementAmount,$row['is_yunzhan']);
                    } elseif ($row->order_status==-1 || $row->order_status==-3 || $row->order_status==1) {
                        $OrderService->statusChange($row['wm_order_sn'],$row['play_order_no'],$row['order_status'],$debitAmount,$settlementAmount,$row['is_yunzhan']);
                    }
                }
                Db::commit();
            } catch (ValidateException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (PDOException $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } catch (Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
                $this->success('操作成功','https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
        }
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        $row->appendRelationAttr('play',['back_money_text','back_money_text2','scheme_no_text']);
        $row->appendRelationAttr('shop',['shop_type_text','contact_user','phone','have_uid','salesman_admin_id','limited_user','is_sjzp','shop_type']);
        $row['shop']['salesman_admin_id'] = $this->db2->name('admin')->where('id',$row['shop']['salesman_admin_id'])->value('nickname');
        $row['proof'] = \app\common\model\OrderProof::where('play_order_no',$row['play_order_no'])->order('id desc')->find();
        $upload_domain = $row['is_yunzhan']==0?config('chbc_upload_domain'):config('upload_domain');
        if ($row['is_yunzhan']==0 && isset($row['proof']['one_image_url'])) {
            $row['proof']['one_image_url'] = $upload_domain.$row['proof']['one_image'];
            $row['proof']['two_image_url'] = $upload_domain.$row['proof']['two_image'];
            $row['proof']['three_image_url'] = $upload_domain.$row['proof']['three_image'];
        }
        if ($row['proof']['supplement']) {
            $supplement = json_decode($row['proof']['supplement'],1);
            foreach ($supplement as $ks => &$sup) {
                if ($ks=='remarks') continue;
                $sup = $upload_domain.$sup;
            }
            $row['proof']['supplement'] = $supplement;
        }
        $handelDesc = ['desc'=>''];
        if (isset($row['proof']['handle_merchant_desc']) && $row['proof']['handle_merchant_desc']) {
            $handelDesc = json_decode($row['proof']['handle_merchant_desc'],1);
            if (isset($handelDesc['img']) && $handelDesc['img']) {
                $img = explode(',', $handelDesc['img']);
                foreach ($img as $key => $value) {
                    $img[$key] = $upload_domain.$value;
                }
                $handelDesc['imgarr'] = $img;
            }
        }
        $adminhandel = ['remark'=>'','optioner'=>'','option'=>'','handle_time'=>''];
        if (isset($row['proof']['handle_admin_desc']) && $row['proof']['handle_admin_desc']) {
            $arr = explode('（', $row['proof']['handle_admin_desc']);
            if (count($arr)==2) {
                $adminhandel['optioner'] = $arr[0];
                $arr = explode('）', $arr[1]);
                $adminhandel['option'] = $arr[1];
            }
            $adminhandel['remark'] = $arr[0];
            $adminhandel['handle_time'] = date('Y-m-d H:i:s',$row['proof']['handle_time']);
        }
        // 当前用户所属用户组
        $auth_groups = $this->db2->name('auth_group_access')->where('uid',$this->auth->id)->value('group_concat(group_id)');
        $grouparr = explode(',', $auth_groups);
        if (in_array('1', $grouparr)) $auth_groups = '1';
        $playuser = $this->db2->name('user')->where('id',$row['shop']['have_uid'])->find();
        // 售后
        $slyj = [2=>"减少订单金额",3=>"需用户提交凭证",];
        $aftersale = $this->db2->name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$row['proof']['play_order_no']])->select();
        if ($aftersale) {
            // 减少渠道结算金额
            $deduction_beans=0;
            $financial_review_num=0;
            foreach ($aftersale as $key => &$value) {
                if ($value['content']) {
                    $value['content'] = json_decode($value['content'],1);
                    if (isset($value['content']['img']) && $value['content']['img']) {
                        $imgarr = explode(',', $value['content']['img']);
                        foreach ($imgarr as &$imgarrs) {
                            $imgarrs = config('upload_domain').$imgarrs;
                        }
                        $value['content']['img'] = $imgarr;
                    }
                    if (isset($value['content']['yh']['file']) && $value['content']['yh']['file']) {
                        $value['content']['yh']['file'] = config('upload_domain').$value['content']['yh']['file'];
                    }
                    if (isset($value['content']['sj']['desc']) && $value['content']['sj']['desc']) {
                        $value['content']['sj']['desc'] = isset($slyj[$value['content']['sj']['desc']])?$slyj[$value['content']['sj']['desc']]:'';
                    }
                    if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                        $deduction_beans+=$value['content']['yh']['amount'];
                        $financial_review_num+=$value['content']['sj']['amount'];
                    }
                    if ($value['type']=='修改渠道结算金额') {
                        $deduction_beans=$value['content']['value'];
                    }
                    if ($value['type']=='修改商家结算金额') {
                        $financial_review_num=$value['content']['value'];
                    }
                }
            }
            if ($deduction_beans>0) $row['proof']['deduction_beans'] = $deduction_beans;
            if ($financial_review_num>0) $row['proof']['financial_review_num'] = $financial_review_num;
        }
        $abnormal_group = ['虚假订单','多平台返现','取消订单/部分退款','实付未满','反馈折叠','反馈未带图/字'];
        // $User = new \app\common\model\User();
        // $user = $User->get($row['user_id']);
        // 用户总订单次数
        $zdd = order_count($row['user_id']);
        // 用户异常订单次数
        $ycdd = (int)$this->db2->name('play_order')->where(['user_id'=>$row['user_id'],'order_status'=>['in',[-4,-6,-7,-8,-9]]])->count();
        $order_status_text = $row['order_status_text'];
        if ($row['order_status_text']=='用户取消') {
            $play_order_log = $this->db2->name('play_order_log')->where(['info'=>'后台取消订单','play_order_no'=>$row['play_order_no']])->find();
            if ($play_order_log) {
                $order_status_text = $play_order_log['create_by'].'取消订单';
            }
        }
        $machine_audit_desc = $row['proof']['machine_audit_desc'];
        $arr = explode('），', $machine_audit_desc);
        foreach ($arr as $key => &$value) {
            $value = str_replace('不合格', '<span style="color:red;">不合格</span>', $value);
        }
        $machine_audit_desc = implode('），', $arr);
        // 是否是必须要复审通过
        // 如果订单满足复审条件的同时是立即配送的就不需要复审
        $ljps = 0;
        if ($machine_audit_desc) {
            if (strpos($machine_audit_desc,'立即配送')) $ljps = 1;
        }
        // 渠道业务员
        $qdywy = '无';
        if ($row['create_by']!='api') {
            if ($row['is_yunzhan']>0) {
                $row['is_yunzhan'] = $this->db2->name('channel')->where('id',$row['is_yunzhan'])->value('name');
                $admin = Db::name('admin')->where('id',$row['service_admin_id'])->find();
                if ($admin['leader']) {
                    $auth_group = Db::name('auth_group')->where(['name'=>$row['is_yunzhan']])->find();
                    $auth_group_access = Db::name('auth_group_access')->where(['group_id'=>$auth_group['id']])->select();
                    foreach ($auth_group_access as $aga) {
                        $qdywyuser = Db::name('admin')->where(['id'=>$aga['uid']])->find();
                        $leader2 = explode(',', trim($qdywyuser['leader2'],','));
                        if (in_array($admin['leader'], $leader2)) $qdywy = $qdywyuser['nickname'];
                    }
                }
            } else {
                $row['is_yunzhan'] = '吃喝不愁';
                $qdywy = '吃喝不愁';
            }
        }
        $is_fushen = is_fushen($row['shop']['is_sjzp'],$zdd,$row['play']['back_money'],$row['play']['is_pay'],$row['user']['is_limited'],$ljps,$row['create_dt'],$row['play']['play_label'],$row['cps_id'],$row['shop']['shop_type']);
        // 商家复审详情
        $fushen = [];
        if ($row['is_fushen']) {
            $fushen = $this->db2->name('play_order_log')->where(['play_order_id'=>$row['id'],'info'=>['in',['客服审核通过，待商家复审','机审通过，待商家复审']]])->find();
        }
        $this->view->assign("qdywy", $qdywy);
        // 是否是重复订单
        $is_effect = $this->db2->name('play_order')->where('wm_order_sn',$row['wm_order_sn'])->count();
        $this->view->assign("is_effect", $is_effect);
        $this->view->assign("order_status_text", $order_status_text);
        $this->view->assign("zdd", $zdd);
        $this->view->assign("ycdd", $ycdd);
        $this->view->assign("slyj", $slyj);
        $this->view->assign("abnormal_group", $abnormal_group);
        $this->view->assign("aftersale", $aftersale);
        $this->view->assign("auth_groups", $auth_groups);
        $this->view->assign("handelDesc", $handelDesc);
        $this->view->assign("adminhandel", $adminhandel);
        $this->view->assign("row", $row);
        $this->view->assign("playuser", $playuser);
        $this->view->assign("machine_audit_desc", $machine_audit_desc);
        $this->view->assign("fushen", $fushen);
        $this->view->assign("is_fushen", $is_fushen);
        return $this->view->fetch();
    }

    public function orderLog($play_order_id, $play_order_no, $info, $create_by, $create_by_id, $is_front=2)
    {
        Db::startTrans();
        try {
            OrderLog::create([
                'play_order_id' => $play_order_id,
                'play_order_no' => $play_order_no,
                'info' => $info,
                'create_by' => $create_by,
                'create_by_id' => $create_by_id,
                'is_front' => $is_front,
            ]);
            Db::commit();
            return true;
        } catch (ValidateException $e) {
            Db::rollback();
            return false;
        } catch (PDOException $e) {
            Db::rollback();
            return false;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    public function OrderAftersale($submit_user, $submit_user_id, $type, $play_order_no, $play_no, $content)
    {
        Db::startTrans();
        try {
            $OrderAftersale = new OrderAftersale();
            $OrderAftersale->save([
                'submit_user' => $submit_user,
                'submit_user_id' => $submit_user_id,
                'type' => $type,
                'play_order_no' => $play_order_no,
                'play_no' => $play_no,
                'content' => $content,
            ]);
            Db::commit();
            return $OrderAftersale['id'];
        } catch (ValidateException $e) {
            Db::rollback();
            return false;
        } catch (PDOException $e) {
            Db::rollback();
            return false;
        } catch (Exception $e) {
            Db::rollback();
            return false;
        }
    }

    public function reject()
    {
        $ids = input('ids/d', 0);
        $handelDesc = input('desc', '');
        $order = $this->model->get($ids);
        if (empty($order) || $order['status'] != 1) $this->error('不可取消');
        $res = (new OrderService())->cancel($order, 4);
        if ($res) $this->success('取消成功');
        else $this->error('取消失败');
    }

    /**
     * 裂变
     * @DateTime 2023-04-12T15:44:26+0800
     * @param    string                   $value [description]
     * @return   [type]                          [description]
     */
    public function fission($user_id,$order)
    {
        Db::startTrans();
        try {
            // 有没有上级用户
            $user = User::get($user_id);
            if (!$user['pid']) {
                Db::commit();
                return ['status'=>1,'msg'=>'没有上级用户'];
            }
            $puser = User::where(['id'=>$user['pid'],'status'=>'normal'])->find();
            if (!$puser) {
                Db::commit();
                return ['status'=>1,'msg'=>'上级用户不存在或被禁用'];
            }
            // 查询是当前用户的第几单,数量包含当前订单
            $count = $this->model->where(['user_id'=>$user_id,'order_status'=>['in',[3,-6]]])->count();
            if ($count==0) {
                Db::rollback();
                return ['status'=>0,'msg'=>'返佣出错'];
            }
            // 裂变配置
            switch ($count) {
                case 1:
                    $invitation_new_reward = $this->db2->name('config')->where(['name'=>'first_order'])->value('value');
                    break;
                case 2:
                    $invitation_new_reward = $this->db2->name('config')->where(['name'=>'second_order'])->value('value');
                    break;
                default:
                    $invitation_new_reward = $this->db2->name('config')->where(['name'=>'third_order'])->value('value');
                    $invitation_new_reward = round($invitation_new_reward*$order['service_charge_amt']*0.01,2);
                    break;
            }
            // 上级用户加上吃豆
            $beans = $invitation_new_reward;
            (new User())->beans($beans,$puser['id'],'下级返利',$order['play_order_no']);
            Db::commit();
            return ['status'=>1,'msg'=>'成功'];
        } catch (Exception $e) {
            Db::rollback();
            return ['status'=>0,'msg'=>$e->getMessage()];
        }
    }

    /**
     * 生成查询所需要的条件,排序方式
     * @param mixed   $searchfields   快速查询的字段
     * @param boolean $relationSearch 是否关联查询
     * @return array
     */
    protected function buildparams($searchfields = null, $relationSearch = null)
    {
        $searchfields = is_null($searchfields) ? $this->searchFields : $searchfields;
        $relationSearch = is_null($relationSearch) ? $this->relationSearch : $relationSearch;
        $search = $this->request->get("search", '');
        $filter = $this->request->get("filter", '');
        $op = $this->request->get("op", '', 'trim');
        $sort = $this->request->get("sort", !empty($this->model) && $this->model->getPk() ? $this->model->getPk() : 'id');
        $order = $this->request->get("order", "DESC");
        $offset = $this->request->get("offset/d", 0);
        $limit = $this->request->get("limit/d", 999999);
        //新增自动计算页码
        $page = $limit ? intval($offset / $limit) + 1 : 1;
        if ($this->request->has("page")) {
            $page = $this->request->get("page/d", 1);
        }
        $this->request->get([config('paginate.var_page') => $page]);
        $filter = (array)json_decode($filter, true);
        // 状态参数过滤掉
        if (isset($filter['service_admin_by'])) {
            unset($filter['service_admin_by']);
        }
        if (isset($filter['play_order_no'])) {
            unset($filter['play_order_no']);
        }
        if (isset($filter['nickname'])) {
            unset($filter['nickname']);
        }
        if (isset($filter['mobile'])) {
            unset($filter['mobile']);
        }
        if (isset($filter['play_type'])) {
            unset($filter['play_type']);
        }
        if (isset($filter['shop_no'])) {
            unset($filter['shop_no']);
        }
        if (isset($filter['shop_name'])) {
            unset($filter['shop_name']);
        }
        if (isset($filter['platform'])) {
            unset($filter['platform']);
        }
        if (isset($filter['lat'])) {
            unset($filter['lat']);
        }
        if (isset($filter['is_yunzhan'])) {
            unset($filter['is_yunzhan']);
        }
        $op = (array)json_decode($op, true);
        $filter = $filter ? $filter : [];
        $where = [];
        $alias = [];
        $bind = [];
        $name = '';
        $aliasName = '';
        if (!empty($this->model) && $this->relationSearch) {
            $name = $this->model->getTable();
            $alias[$name] = \think\Loader::parseName(basename(str_replace('\\', '/', get_class($this->model))));
            $aliasName = $alias[$name] . '.';
        }
        $sortArr = explode(',', $sort);
        foreach ($sortArr as $index => & $item) {
            $item = stripos($item, ".") === false ? $aliasName . trim($item) : $item;
        }
        unset($item);
        $sort = implode(',', $sortArr);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $where[] = [$aliasName . $this->dataLimitField, 'in', $adminIds];
        }
        if ($search) {
            $searcharr = is_array($searchfields) ? $searchfields : explode(',', $searchfields);
            foreach ($searcharr as $k => &$v) {
                $v = stripos($v, ".") === false ? $aliasName . $v : $v;
            }
            unset($v);
            $where[] = [implode("|", $searcharr), "LIKE", "%{$search}%"];
        }
        $index = 0;
        foreach ($filter as $k => $v) {
            if (!preg_match('/^[a-zA-Z0-9_\-\.]+$/', $k)) {
                continue;
            }
            $sym = isset($op[$k]) ? $op[$k] : '=';
            if (stripos($k, ".") === false) {
                $k = $aliasName . $k;
            }
            $v = !is_array($v) ? trim($v) : $v;
            $sym = strtoupper(isset($op[$k]) ? $op[$k] : $sym);
            //null和空字符串特殊处理
            if (!is_array($v)) {
                if (in_array(strtoupper($v), ['NULL', 'NOT NULL'])) {
                    $sym = strtoupper($v);
                }
                if (in_array($v, ['""', "''"])) {
                    $v = '';
                    $sym = '=';
                }
            }

            switch ($sym) {
                case '=':
                case '<>':
                    $where[] = [$k, $sym, (string)$v];
                    break;
                case 'LIKE':
                case 'NOT LIKE':
                case 'LIKE %...%':
                case 'NOT LIKE %...%':
                    $where[] = [$k, trim(str_replace('%...%', '', $sym)), "{$v}%"];
                    break;
                case '>':
                case '>=':
                case '<':
                case '<=':
                    $where[] = [$k, $sym, intval($v)];
                    break;
                case 'FINDIN':
                case 'FINDINSET':
                case 'FIND_IN_SET':
                    $v = is_array($v) ? $v : explode(',', str_replace(' ', ',', $v));
                    $findArr = array_values($v);
                    foreach ($findArr as $idx => $item) {
                        $bindName = "item_" . $index . "_" . $idx;
                        $bind[$bindName] = $item;
                        $where[] = "FIND_IN_SET(:{$bindName}, `" . str_replace('.', '`.`', $k) . "`)";
                    }
                    break;
                case 'IN':
                case 'IN(...)':
                case 'NOT IN':
                case 'NOT IN(...)':
                    $where[] = [$k, str_replace('(...)', '', $sym), is_array($v) ? $v : explode(',', $v)];
                    break;
                case 'BETWEEN':
                case 'NOT BETWEEN':
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr, function($v){
                        return $v != '' && $v !== false && $v !== null;
                    })) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'BETWEEN' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'BETWEEN' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $where[] = [$k, $sym, $arr];
                    break;
                case 'RANGE':
                case 'NOT RANGE':
                    $v = str_replace(' - ', ',', $v);
                    $arr = array_slice(explode(',', $v), 0, 2);
                    if (stripos($v, ',') === false || !array_filter($arr)) {
                        continue 2;
                    }
                    //当出现一边为空时改变操作符
                    if ($arr[0] === '') {
                        $sym = $sym == 'RANGE' ? '<=' : '>';
                        $arr = $arr[1];
                    } elseif ($arr[1] === '') {
                        $sym = $sym == 'RANGE' ? '>=' : '<';
                        $arr = $arr[0];
                    }
                    $tableArr = explode('.', $k);
                    if (count($tableArr) > 1 && $tableArr[0] != $name && !in_array($tableArr[0], $alias) && !empty($this->model)) {
                        //修复关联模型下时间无法搜索的BUG
                        $relation = Loader::parseName($tableArr[0], 1, false);
                        $alias[$this->model->$relation()->getTable()] = $tableArr[0];
                    }
                    $where[] = [$k, str_replace('RANGE', 'BETWEEN', $sym) . ' TIME', $arr];
                    break;
                case 'NULL':
                case 'IS NULL':
                case 'NOT NULL':
                case 'IS NOT NULL':
                    $where[] = [$k, strtolower(str_replace('IS ', '', $sym))];
                    break;
                default:
                    break;
            }
            $index++;
        }
        if (!empty($this->model)) {
            $this->model->alias($alias);
        }
        $model = $this->model;
        $where = function ($query) use ($where, $alias, $bind, &$model) {
            if (!empty($model)) {
                $model->alias($alias);
                $model->bind($bind);
            }
            foreach ($where as $k => $v) {
                if (is_array($v)) {
                    call_user_func_array([$query, 'where'], $v);
                } else {
                    $query->where($v);
                }
            }
        };
        return [$where, $sort, $order, $offset, $limit, $page, $alias, $bind];
    }

    public function limited()
    {
        $is_limited = input('is_limited',0);
        $play_order_no = input('play_order_no',0);
        if (!$is_limited || !$play_order_no) {
            $this->error('参数不正确');
        }
        $play_order_no = trim($play_order_no);
        $order = $this->db2->name('play_order')->where(['play_order_no'=>$play_order_no])->field('id,user_id,shop_no')->find();
        if (!$order) {
            $this->error('未查询到订单');
        }
        $shop = $this->db2->name('shop')->where(['shop_no'=>$order['shop_no']])->field('id,limited_user')->find();
        if (!$shop) {
            $this->error('未查询到店铺');
        }
        $user = $this->db2->name('user')->where(['id'=>$order['user_id']])->field('id')->find();
        if (!$user) {
            $this->error('未查询到用户');
        }
        $data = [];
        if ($is_limited=='true') {
            if (!$shop['limited_user']) {
                $data['limited_user'] = '|'.$order['user_id'].'|';
                $data['update_by'] = $this->auth->id;
                $data['update_dt'] = date('Y-m-d H:i:s');
            } else {
                $limited_user = trim($shop['limited_user'],'|');
                $arr = explode('|', $limited_user);
                if (count($arr) && !in_array($order['user_id'], $arr)) {
                    $arr[] = $order['user_id'];
                    $data['limited_user'] = implode('|', $arr);
                    $data['limited_user'] = '|'.$data['limited_user'].'|';
                    $data['update_by'] = $this->auth->id;
                    $data['update_dt'] = date('Y-m-d H:i:s');
                }
            }
        } elseif ($is_limited=='false') {
            if ($shop['limited_user']) {
                $limited_user = trim($shop['limited_user'],'|');
                $arr = explode('|', $limited_user);
                if (count($arr) && in_array($order['user_id'], $arr)) {
                    foreach ($arr as $key => $value) {
                        if ($order['user_id']==$value) unset($arr[$key]);
                    }
                    if ($arr) {
                        $data['limited_user'] = implode('|', $arr);
                        $data['limited_user'] = '|'.$data['limited_user'].'|';
                    } else {
                        $data['limited_user'] = '';
                    }
                    $data['update_by'] = $this->auth->id;
                    $data['update_dt'] = date('Y-m-d H:i:s');
                }
            }
        }
        if ($data) {
            Db::name('shop')->where(['shop_no'=>$order['shop_no']])->update($data);
            $this->success('成功');
        }
        $this->error('失败');
    }


    public function updateparam()
    {
        $param = $this->request->param();
        if (!isset($param['name']) || !isset($param['value']) || !isset($param['orderid']) || !isset($param['shopno'])) {
            $this->error('参数有误');
        }
        \think\Log::write('管理员id:'.$this->auth->id);
        if ($param['name']=='shopid') {
            $order = $this->db2->name('play_order')->where('id',$param['orderid'])->field('id,shop_no')->find();
            $shop = $this->db2->name('shop')->where('id',$param['value'])->field('id,shop_name,shop_no')->find();
            if (!$shop) {
                $this->error('店铺不存在');
            }
            if ($order['shop_no']==$shop['shop_no']) {
                $this->error('店铺id没有变化');
            }
            Db::name('play_order')->where('id',$param['orderid'])->update(['shop_no'=>$shop['shop_no']]);
            $this->success('成功','',$shop['shop_name']);
        } elseif ($param['name']=='shopplatform_no') {
            $shop = $this->db2->name('shop')->where('shop_no',$param['shopno'])->field('shop_name')->find();
            if (!$shop) {
                $this->error('店铺不存在');
            }
            $shop_platform = $this->db2->name('shop_platform')->field('platform_no')->where('shop_no',$param['shopno'])->find();
            if (!$shop_platform) {
                $this->error('进店id不存在');
            }
            if ($shop_platform['platform_no']==$param['value']) {
                $this->error('进店id没有变化');
            }
            Db::name('shop_platform')->where('shop_no',$param['shopno'])->update(['platform_no'=>$param['value']]);
            $this->success('成功');
        } elseif ($param['name']=='proofwm_order_sn') {
            $order = $this->db2->name('play_order')->where('id',$param['orderid'])->field('play_order_no,wm_order_sn,yunzhan_order_no,is_yunzhan')->find();
            if ($order['is_yunzhan']==2) {
                $proof = $this->db2->name('play_order_proof')->where('play_order_no',$order['yunzhan_order_no'])->field('play_order_no,wm_order_sn,id')->order('id DESC')->find();
            } else {
                $proof = $this->db2->name('play_order_proof')->where('play_order_no',$order['play_order_no'])->field('play_order_no,wm_order_sn,id')->order('id DESC')->find();
            }
            if (!$order || !$proof) {
                $this->error('订单不存在');
            }
            Db::name('play_order')->where('id',$param['orderid'])->update(['wm_order_sn'=>$param['value']]);
            Db::name('play_order_proof')->where('play_order_no',$proof['play_order_no'])->update(['wm_order_sn'=>$param['value']]);
            $this->success('成功');
        }
        $this->error('失败');
    }


    public function add()
    {
        // 分发渠道
        $channel = $this->db2->name('channel')->where(['status'=>1])->select();
        $this->view->assign("channel", $channel);
        $importorderurl = config('connect_domain').'/index/cront/importorder?token='.$this->auth->token2;
        $this->view->assign("importorderurl", $importorderurl);
        return $this->view->fetch();
    }

    // 修改渠道结算金额
    public function deduction_beansevent()
    {
        $orderid = input('orderid');
        $value = input('value');
        $value = floatval($value);
        $order = $this->model->where('id',$orderid)->field('play_order_no,wm_order_sn,yunzhan_order_no,is_yunzhan,play_no,user_id,actual_rebate_amt,order_status,is_pay,rebate_amt,service_charge_amt')->find();
        // if ($order['order_status']!=-9 || $order['is_pay']==1) $this->error('订单状态有误');
        $orderProof = orderProof::where('play_order_no',$order['play_order_no'])->field('play_order_no,wm_order_sn,id,deduction_beans')->order('id DESC')->find();
        
        $User = new User();
        if ($value>$orderProof['deduction_beans']) {
            // 扣除少扣的吃豆
            $beans = -1*($value-$orderProof['deduction_beans']);
            $User->beans($beans,$order['user_id'],'修改渠道结算金额',$orderProof['play_order_no']);
        }
        if ($value<$orderProof['deduction_beans']) {
            // 加上多扣的吃豆
            $beans = -1*($orderProof['deduction_beans']-$value);
            $User->beans($beans,$order['user_id'],'修改渠道结算金额',$orderProof['play_order_no']);
        }

        $orderProof->deduction_beans = floatval($value);
        $orderProof->save();
        // 售后事件
        $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'修改渠道结算金额',$orderProof['play_order_no'],$order['play_no'],'{"value":'.$value.'}');
        // 减少渠道结算金额
        $aftersale = Db::name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$order['play_order_no']])->select();
        $deduction_beans=0;
        $financial_review_num=0;
        if ($aftersale) {
            foreach ($aftersale as $key => &$value) {
                if ($value['content']) {
                    $value['content'] = json_decode($value['content'],1);
                    if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                        $deduction_beans+=$value['content']['yh']['amount'];
                        $financial_review_num+=$value['content']['sj']['amount'];
                    }
                    if ($value['type']=='修改渠道结算金额') {
                        $deduction_beans=$value['content']['value'];
                        break;
                    }
                    if ($value['type']=='修改商家结算金额') {
                        $financial_review_num=$value['content']['value'];
                        break;
                    }
                }
            }
        }
        // 渠道结算金额
        $deduction_beans = $orderProof->deduction_beans;
        // 商家应该支付的：商家需要付的减商家扣款的
        $yf = round($order['rebate_amt']-$financial_review_num,2);
        // 渠道应该获得的
        $qd = round($order['rebate_amt']-$order['service_charge_amt'],2);
        // 渠道实际获得的
        $order->actual_rebate_amt2 = round($qd-$deduction_beans,2);
        // 重新计算后的平台服务费
        $order->service_charge_amt2 = round($yf-$order->actual_rebate_amt2,2);
        $order->save();
        $this->success('成功');

    }

    // 修改商家结算金额
    public function financial_review_numevent()
    {
        $orderid = input('orderid');
        $value = input('value');
        $value = floatval($value);
        $order = $this->model->where('id',$orderid)->field('play_order_no,wm_order_sn,yunzhan_order_no,is_yunzhan,play_no,user_id,actual_rebate_amt,order_status,is_pay,rebate_amt,service_charge_amt,shop_no')->find();
        // if ($order['order_status']!=-9 || $order['is_pay']==1) $this->error('订单状态有误');
        $orderProof = orderProof::where('play_order_no',$order['play_order_no'])->field('play_order_no,wm_order_sn,id,financial_review_num')->order('id DESC')->find();

        $money = $value-$orderProof['financial_review_num'];
        $order->actual_rebate_amt = $order->actual_rebate_amt-$money;
        $order->save();

        $orderProof->financial_review_num = floatval($value);
        $orderProof->save();
        // 售后事件
        $OrderAftersaleId = $this->OrderAftersale($this->auth->nickname,$this->auth->id,'修改商家结算金额',$orderProof['play_order_no'],$order['play_no'],'{"value":'.$value.'}');
        // 减少渠道结算金额
        $aftersale = Db::name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$order['play_order_no']])->select();
        $deduction_beans=0;
        $financial_review_num=0;
        if ($aftersale) {
            foreach ($aftersale as $key => &$value) {
                if ($value['content']) {
                    $value['content'] = json_decode($value['content'],1);
                    if ($value['type']=='客服审核拟取消或扣吃豆通过') {
                        $deduction_beans+=$value['content']['yh']['amount'];
                        $financial_review_num+=$value['content']['sj']['amount'];
                    }
                    if ($value['type']=='修改渠道结算金额') {
                        $deduction_beans=$value['content']['value'];
                        break;
                    }
                    if ($value['type']=='修改商家结算金额') {
                        $financial_review_num=$value['content']['value'];
                        break;
                    }
                }
            }
        }
        // 商家结算金额
        $financial_review_num = $orderProof->financial_review_num;
        // 商家应该支付的：商家需要付的减商家扣款的
        $yf = round($order['rebate_amt']-$financial_review_num,2);
        // 渠道应该获得的
        $qd = round($order['rebate_amt']-$order['service_charge_amt'],2);
        // 渠道实际获得的
        $order->actual_rebate_amt2 = round($qd-$deduction_beans,2);
        // 重新计算后的平台服务费
        $order->service_charge_amt2 = round($yf-$order->actual_rebate_amt2,2);
        $order->save();
        if ($order['is_pay']==1) {
            // 先计算之前总共扣了多少
            $sum = (float)Db::name('user_money_log')->where(['tran_no'=>$orderProof['play_order_no'],'log_type'=>7])->value('sum(money)');
            // 计算本次应该给商家退多少
            $back = round($orderProof['financial_review_num']-$sum,2);
            $shop = Db::name('shop')->where('shop_no',$order['shop_no'])->find();
            if (!isset($shop['phone']) || !$shop['phone']) $this->error('相关店铺信息需要完善');
            $merchant = Db::name('user')->where('mobile',$shop['phone'])->find();
            // 如果有对应商家，则给商家加上余额，如果没有对应商家，插入一条手机号流水
            if ($merchant) {
                $User = new User();
                $res = $User->money($back, $merchant['id'], '财务修改账单金额', $orderProof['play_order_no']);
            } else {
                // 先查询这个手机号之前有没有流水
                $before = (float)Db::name('user_money_log')->where(['phone'=>$shop['phone'],'log_status'=>0])->order('id desc')->value('after_money');
                $money = $back;
                $after = function_exists('bcadd') ? bcadd($before, $money, 2) : $before + $money;
                //写入日志
                \app\common\model\UserMoneyLog::create(['phone' => $shop['phone'], 'money' => $money, 'before_money' => $before, 'after_money' => $after, 'memo' => '财务修改账单金额','log_type'=>7,'log_status'=>0,'tran_no'=>$orderProof['play_order_no']]);
            }
        }
        $this->success('成功');
    }



    public function export()
    {
        if ($this->request->isPost()) {
            set_time_limit(0);
            $search = $this->request->post('search');
            $ids = $this->request->post('ids');
            $filter = $this->request->post('filter');
            $op = $this->request->post('op');
            $columns = $this->request->post('columns');
            $start = $this->request->post('start');
            $end = $this->request->post('end');
            $type = $this->request->post('type');//type为已完成待支付订单时，导出is_pay==0,order_status in (3,6,-9),create_dt<date('Y-m-d')的订单

            //$excel = new PHPExcel();
            $spreadsheet = new Spreadsheet();

            $spreadsheet->getProperties()
                ->setCreator($this->auth->nickname)
                ->setLastModifiedBy($this->auth->nickname)
                ->setTitle("订单列表")
                ->setSubject("订单列表");
            $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
            $spreadsheet->getDefaultStyle()->getFont()->setSize(12);

            $worksheet = $spreadsheet->setActiveSheetIndex(0);
            $whereIds = $ids == 'all' ? '1=1' : ['id' => ['in', explode(',', $ids)]];
            $this->request->get(['search' => $search, 'ids' => $ids, 'filter' => $filter, 'op' => $op]);
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $line = 1;
            $ShopModel = new \app\admin\model\Shop();
            $PlayModel = new \app\admin\model\Play();
            $OrderProof = new OrderProof();
            $decode = json_decode($filter,1);
            if ($type=='已完成待支付订单') {
                $where2 = 'is_pay=0 and order_status in (3,6,-9) and create_dt<"'.date('Y-m-d').'"';
            } else {
                if (!$start) $start=0;
                if (!$end) $end=100000000;
                $where2 = 'id>='.$start.' and id<='.$end;
                if (isset($decode['play_order_no']) && $decode['play_order_no']) {
                    if (intval($decode['play_order_no'])==0) {
                        $where2 .= ' and yunzhan_order_no = "'.$decode['play_order_no'].'"';
                    } else {
                        $where2 .= ' and play_order_no = "'.$decode['play_order_no'].'"';
                    }
                }
                if (isset($decode['service_admin_by']) && $decode['service_admin_by']) {
                    $where2 .= ' and service_admin_by = "'.$decode['service_admin_by'].'"';
                }
                if (isset($decode['shop_no']) && $decode['shop_no']) {
                    $shop_no = $this->db2->name('shop')->where('id',$decode['shop_no'])->value('shop_no');
                    if ($shop_no) {
                        $where2 .= ' and shop_no = "'.$shop_no.'"';
                    }
                }
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $list = $this->db2->name('play_order')
                ->where($where)
                ->where($where2)
                ->order($sort, $order)->select();

            foreach ($list as &$row) {
                $row['scheme_no_text'] = $row['scheme_no'];
                $row['lat'] = order_count($row['user_id']);
                $row['platform'] = config('platform')[$row['platform_no']];
                $row['is_yunzhan'] = $row['is_yunzhan']==0?'吃喝不愁':$this->db2->name('channel')->where('id',$row['is_yunzhan'])->value('name');
                $row['shop_no'] = $ShopModel->where('shop_no',$row['shop_no'])->value('id');
                // 渠道结算金额
                if (in_array($row['order_status'],[-8,-9])) {
                    $row['actual_rebate_amt'] = $row['actual_rebate_amt2'];
                    $deduction_beans = round($row['rebate_amt']-$row['service_charge_amt']-$row['actual_rebate_amt'],2);
                    $row['service_charge_amt'] = $row['service_charge_amt2'];
                    $row['rebate_amt'] = round($row['service_charge_amt']+$row['actual_rebate_amt'],2);
                } elseif ($row['order_status']==-4) {
                    $row['actual_rebate_amt'] = 0;
                    $row['rebate_amt'] = 0;
                    $row['service_charge_amt'] = 0;
                    $deduction_beans = round($value['rebate_amt']-$value['service_charge_amt']-$value['actual_rebate_amt'],2);
                } else {
                    $row['rebate_amt'] = round($row['service_charge_amt']+$row['actual_rebate_amt'],2);
                    $deduction_beans = 0;
                }
            }
            $worksheet->setCellValueByColumnAndRow(1, 1, 'ID');
            $worksheet->setCellValueByColumnAndRow(2, 1, '平台单号');
            $worksheet->setCellValueByColumnAndRow(3, 1, '店铺名称');
            $worksheet->setCellValueByColumnAndRow(4, 1, '店铺id');
            $worksheet->setCellValueByColumnAndRow(5, 1, '渠道名称');
            $worksheet->setCellValueByColumnAndRow(6, 1, '外卖平台');
            $worksheet->setCellValueByColumnAndRow(7, 1, '外卖单号');
            $worksheet->setCellValueByColumnAndRow(8, 1, '商家需支付金额');
            $worksheet->setCellValueByColumnAndRow(9, 1, '渠道结算金额');
            $worksheet->setCellValueByColumnAndRow(10, 1, '减少渠道结算金额');
            $worksheet->setCellValueByColumnAndRow(11, 1, '服务费');
            $worksheet->setCellValueByColumnAndRow(12, 1, '所属业务员');
            $worksheet->setCellValueByColumnAndRow(13, 1, '是否结算');
            $worksheet->setCellValueByColumnAndRow(14, 1, '抢单时间');
            $worksheet->setCellValueByColumnAndRow(15, 1, '状态');
            $channel = $this->db2->name('channel')->select();
            $is_yunzhan = [];
            foreach ($channel as $key => $value) {
                $is_yunzhan[$value['id']] = $value['name'];
            }
            foreach ($list as $key => $value) {
                $shop_id = $this->db2->name('shop')->where('shop_no',$value['shop_no'])->value('id');
                $value['is_yunzhan'] = $value['is_yunzhan']==0?'吃喝不愁':$is_yunzhan[$value['is_yunzhan']];
                $value['platform'] = config('platform')[$value['platform_no']];
                $worksheet->setCellValueByColumnAndRow(1, $key+2, $value['id']);
                $worksheet->setCellValueByColumnAndRow(2, $key+2, "'".$value['play_order_no']);
                $worksheet->setCellValueByColumnAndRow(3, $key+2, $value['shop_name']);
                $worksheet->setCellValueByColumnAndRow(4, $key+2, $shop_id);
                $worksheet->setCellValueByColumnAndRow(5, $key+2, $value['is_yunzhan']);
                $worksheet->setCellValueByColumnAndRow(6, $key+2, $value['platform']);
                $worksheet->setCellValueByColumnAndRow(7, $key+2, "'".$value['wm_order_sn']);
                $worksheet->setCellValueByColumnAndRow(8, $key+2, round($value['service_charge_amt']+$value['actual_rebate_amt'],2));
                $worksheet->setCellValueByColumnAndRow(9, $key+2, $value['actual_rebate_amt']);
                $worksheet->setCellValueByColumnAndRow(10, $key+2, $deduction_beans);
                $worksheet->setCellValueByColumnAndRow(11, $key+2, $value['service_charge_amt']);
                $worksheet->setCellValueByColumnAndRow(12, $key+2, $value['service_admin_by']);
                $worksheet->setCellValueByColumnAndRow(13, $key+2, $value['is_pay']==0?'未结算':'已结算');
                $worksheet->setCellValueByColumnAndRow(14, $key+2, date('Y-m-d H:i:s',$value['place_time']));
                $worksheet->setCellValueByColumnAndRow(15, $key+2, $this->model->getOrderStatusTextAttr($value['order_status'],''));
            }
     
     
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            if ($type=='已完成待支付订单') {
                header('Content-Disposition: attachment;filename="'. date('Y-m-d') . '已完成待支付订单.xlsx"');
            } else {
                header('Content-Disposition: attachment;filename="'. date('Y-m-d') . '订单列表.xlsx"');
            }
            header('Cache-Control: max-age=0');
     
            $write = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
            $write->save('php://output');
            return ;
            
            $first = array_keys($list[0]);
            foreach ($first as $index => $item) {
                $worksheet->setCellValueByColumnAndRow($index, 1, __($item));
            }
            
            // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(__DIR__ . '/muban/test.xls');  //读取模板
            $worksheet = $spreadsheet->getActiveSheet();     //指向激活的工作表
            $worksheet->setTitle('订单列表');

            // for($i=0;$i<$total;++$i){ 
            //     //向模板表中写入数据
            //     $worksheet->setCellValue('A1', '模板测试内容');   //送入A1的内容
            //     $worksheet->getCell('B2')->setValue($result['rows'][$i]['week']);    //星期
            //     $worksheet->getCell('d2')->setValue($result['rows'][$i]['genderdata']);  //性别
            //     $worksheet->getCell('f2')->setValue($result['rows'][$i]['hobbydata']);  //爱好
            //     $worksheet->getCell('b3')->setValue($result['rows'][$i]['title']);  //标题
            //     $worksheet->getCell('b4')->setValue($result['rows'][$i]['content']);  //内容
                
                
            // }  
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
            //下载文档
            header('Content-Type: application/vnd.ms-excel');
            header('Content-Disposition: attachment;filename="'. date('Y-m-d') . '订单列表.xlsx"');
            header('Cache-Control: max-age=0');
            $writer = new Xlsx($spreadsheet);
            $writer->save('php://output');      

            return;
        }
    }



    public function export2()
    {
        $ShopModel = new \app\admin\model\Shop();
        $PlayModel = new \app\admin\model\Play();
        $db2 = Db::connect(config('database.db2'));
        set_time_limit(0);
        ini_set('memory_limit', '256M');

        //$excel = new PHPExcel();
        $spreadsheet = new Spreadsheet();

        $spreadsheet->getProperties()
            ->setCreator($this->auth->nickname)
            ->setLastModifiedBy($this->auth->nickname)
            ->setTitle("订单列表")
            ->setSubject("订单列表");
        $spreadsheet->getDefaultStyle()->getFont()->setName('Microsoft Yahei');
        $spreadsheet->getDefaultStyle()->getFont()->setSize(12);

        $worksheet = $spreadsheet->setActiveSheetIndex(0);
        $middlemanarr = [];
        $middleman = $db2->name('middleman')->field('id,rebate_amt')->select();
        foreach ($middleman as $man) {
            $middlemanarr[$man['id']] = $man['rebate_amt'];
        }
        $channelarr = [];
        $channel = $db2->name('channel')->select();
        foreach ($channel as $cha) {
            $channelarr[$cha['id']] = $cha['name'];
        }
        $sql = "SELECT id,play_order_no,shop_name,is_yunzhan,platform_no,wm_order_sn,rebate_amt,actual_rebate_amt,service_charge_amt,create_dt,order_status,shop_no,actual_rebate_amt2,service_charge_amt2 FROM chbc_play_order where create_dt > '2025-01-01 00:00:00' AND create_dt < '2025-07-01 00:00:00' and order_status in (-7,-8,-9,-4)";
        $list = $db2->query($sql);
        $worksheet->setCellValueByColumnAndRow(1, 1, 'ID');
        $worksheet->setCellValueByColumnAndRow(2, 1, '平台单号');
        $worksheet->setCellValueByColumnAndRow(3, 1, '店铺名称');
        $worksheet->setCellValueByColumnAndRow(4, 1, '渠道名称');
        $worksheet->setCellValueByColumnAndRow(5, 1, '下单平台');
        $worksheet->setCellValueByColumnAndRow(6, 1, '外卖单号');
        $worksheet->setCellValueByColumnAndRow(7, 1, '代收商家支付金额');
        $worksheet->setCellValueByColumnAndRow(8, 1, '代付用户返现金额');
        $worksheet->setCellValueByColumnAndRow(9, 1, '减少渠道结算金额');
        $worksheet->setCellValueByColumnAndRow(10, 1, '平台服务费');
        $worksheet->setCellValueByColumnAndRow(11, 1, '经纪人佣金');
        $worksheet->setCellValueByColumnAndRow(12, 1, '抢单时间');
        $worksheet->setCellValueByColumnAndRow(13, 1, '状态');
        foreach ($list as $key => $row) {
            $proof = $db2->name('play_order_proof')->where('play_order_no',$row['play_order_no'])->order('id desc')->field('one_image,two_image,three_image,wm_order_sn,machine_audit_desc,machine_audit_state,deduction_beans,financial_review,financial_review_num')->find();
            $row['proof'] = $proof;
            // $row['lat'] = order_count($row['user_id']);
            $row['platform'] = config('platform')[$row['platform_no']];
            $row['is_yunzhan'] = $row['is_yunzhan']==0?'吃喝不愁':$channelarr[$row['is_yunzhan']];
            $shop = $db2->name('shop')->where('shop_no',$row['shop_no'])->field('id,shop_name,middleman_id')->find();
            $row['shop_no'] = $shop['id'];
            $row['shop_name'] = $shop['shop_name'];
            // 减少渠道结算金额
            // $aftersale = $db2->name('play_order_aftersale')->order('id asc')->where(['play_order_no'=>$row['play_order_no']])->select();
            // if ($aftersale) {
            //     $deduction_beans=0;
            //     $financial_review_num=0;
            //     foreach ($aftersale as &$value) {
            //         if ($value['content']) {
            //             $value['content'] = json_decode($value['content'],1);
            //             if ($value['type']=='客服审核拟取消或扣吃豆通过') {
            //                 $deduction_beans+=$value['content']['yh']['amount'];
            //                 $financial_review_num+=$value['content']['sj']['amount'];
            //             }
            //             if ($value['type']=='修改渠道结算金额') {
            //                 $deduction_beans=$value['content']['value'];
            //             }
            //             if ($value['type']=='修改商家结算金额') {
            //                 $financial_review_num=$value['content']['value'];
            //             }
            //         }
            //     }
            //     if ($deduction_beans>0) $row['proof']['deduction_beans'] = $deduction_beans;
            //     if ($financial_review_num>0) $row['proof']['financial_review_num'] = $financial_review_num;
            // }
            // 渠道结算金额
            if (in_array($row['order_status'],[-8,-9])) {
                // // 商家应该支付的：商家需要付的减商家扣款的
                // $yf = round($row['rebate_amt']-$row['proof']['financial_review_num'],2);
                // // 渠道应该获得的
                // $qd = round($row['rebate_amt']-$row['service_charge_amt'],2);
                // // 渠道实际获得的
                // $row['actual_rebate_amt'] = round($qd-$row['proof']['deduction_beans'],2);
                // // 平台服务费
                // $row['service_charge_amt'] = round($yf-$row['actual_rebate_amt'],2);
                
                // $row['rebate_amt'] = $yf;
                $row['actual_rebate_amt'] = $row['actual_rebate_amt2'];
                $row['proof']['deduction_beans'] = round($row['rebate_amt']-$row['service_charge_amt']-$row['actual_rebate_amt'],2);
                $row['service_charge_amt'] = $row['service_charge_amt2'];
                $row['rebate_amt'] = round($row['service_charge_amt']+$row['actual_rebate_amt'],2);
            } elseif ($row['order_status']==-4) {
                $row['actual_rebate_amt'] = 0;
                $row['rebate_amt'] = 0;
                $row['service_charge_amt'] = 0;
            } else {
                $row['rebate_amt'] = round($row['service_charge_amt']+$row['actual_rebate_amt'],2);
            }
            // 经纪人佣金
            $row['service_admin_id'] = 0;
            if ($shop['middleman_id']) {
                $row['service_admin_id'] = isset($middlemanarr[$shop['middleman_id']])?floatval($middlemanarr[$shop['middleman_id']]):0;
            }
            $worksheet->setCellValueByColumnAndRow(1, $key+2, $row['id']);
            $worksheet->setCellValueByColumnAndRow(2, $key+2, "'".$row['play_order_no']);
            $worksheet->setCellValueByColumnAndRow(3, $key+2, $row['shop_name']);
            $worksheet->setCellValueByColumnAndRow(4, $key+2, $row['is_yunzhan']);
            $worksheet->setCellValueByColumnAndRow(5, $key+2, $row['platform']);
            $worksheet->setCellValueByColumnAndRow(6, $key+2, "'".$row['wm_order_sn']);
            $worksheet->setCellValueByColumnAndRow(7, $key+2, $row['rebate_amt']);
            $worksheet->setCellValueByColumnAndRow(8, $key+2, $row['actual_rebate_amt']);
            $worksheet->setCellValueByColumnAndRow(9, $key+2, $row['proof']['deduction_beans']);
            $worksheet->setCellValueByColumnAndRow(10, $key+2, $row['service_charge_amt']);
            $worksheet->setCellValueByColumnAndRow(11, $key+2, $row['service_admin_id']);
            $worksheet->setCellValueByColumnAndRow(12, $key+2, $row['create_dt']);
            $worksheet->setCellValueByColumnAndRow(13, $key+2, $row['order_status']);
        }
 
 
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="'. date('Y-m-d') . '订单列表.xlsx"');
        header('Cache-Control: max-age=0');
 
        $write = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
        $write->save('php://output');
        return ;
        
        $first = array_keys($list[0]);
        foreach ($first as $index => $item) {
            $worksheet->setCellValueByColumnAndRow($index, 1, __($item));
        }
        
        // $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load(__DIR__ . '/muban/test.xls');  //读取模板
        $worksheet = $spreadsheet->getActiveSheet();     //指向激活的工作表
        $worksheet->setTitle('订单列表');
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xls');
        //下载文档
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="'. date('Y-m-d') . '订单列表.xlsx"');
        header('Cache-Control: max-age=0');
        $writer = new Xlsx($spreadsheet);
        $writer->save('php://output');      

        return;
        
    }

}
